package com.coldlz.mmp.ssl;

import org.bouncycastle.pkcs.PKCS10CertificationRequest;

import java.io.IOException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.Base64;
import java.util.List;

public class X509CertificateUtil {

    // 将X509Certificate对象转化为证书字符串
    public static String toFileStr(X509Certificate certificate)  {
        StringBuilder builder = new StringBuilder();
        builder.append("-----BEGIN CERTIFICATE-----").append('\n');
        String content = null;
        try {
            content = Base64.getEncoder().encodeToString(certificate.getEncoded());
        } catch (CertificateEncodingException e) {
            throw new RuntimeException(e);
        }
        appendContent(content, builder);
        builder.append("-----END CERTIFICATE-----");
        return builder.toString();
    }

    public static String toFileStr(PKCS10CertificationRequest csr) throws IOException {
        StringBuilder builder = new StringBuilder();
        builder.append("-----BEGIN CERTIFICATE REQUEST-----").append('\n');
        String content = Base64.getEncoder().encodeToString(csr.getEncoded());
        appendContent(content, builder);
        builder.append("-----END CERTIFICATE REQUEST-----");
        return builder.toString();
    }


    private static void appendContent(String content, StringBuilder builder) {
        List<String> lines = Util.splitString(content);
        for (String line : lines) {
            builder.append(line).append('\n');
        }
    }
}
